<?php
/**
 * 操作记录
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/7/13
 * @copyright PanxSoft Inc.
 */
namespace App\Http\Controllers\App;

use App\Http\Controllers\ApiController;
use App\Http\Requests\App\OperateLog\StoreGuestAddCartRequest;
use App\Models\Customer\DeviceAccount;
use App\Models\Logger\LogType;
use App\Models\Logger\OperateLog;
use App\Models\Panx\Product;
use App\Services\Utils\Guard;

class OperateLogController extends ApiController
{
    const ROUTES = [
        'guest-add-cart' => 'app.operate-log.store.guest-add-cart',
    ];

    /**
     * 记录游客加入购物车的动作
     * @test
     *
     * @param StoreGuestAddCartRequest $request
     *
     * @throws \Exception
     * @return array|\Illuminate\Http\Response
     */
    public function storeGuestAddCart(StoreGuestAddCartRequest $request)
    {
        $prod = (new Product)->find($request->product_id);
            $this->checkItemExist($prod, 'product');

        $dev_acnt = Guard::deviceAccount();
            $this->checkProdDeviceIsSameCustomer($prod, $dev_acnt);

        $type_id = LogType::DEV_ACNT_GUEST_ADD_CART;
        $log_msg = LogType::REMARK_MAP[LogType::DEV_ACNT_GUEST_ADD_CART];

        $log = OperateLog::createLog(
            $dev_acnt, $prod, $type_id, $log_msg, $dev_acnt->customer_id, $dev_acnt->store_id
        );

        return $this->response(compact('log'));
    }

    /**
     * @param Product $prod
     * @param DeviceAccount $dev_acnt
     *
     * @throws \Exception
     */
    private function checkProdDeviceIsSameCustomer(Product $prod,
                                                   DeviceAccount $dev_acnt): void
    {
        $this->checkIsTrue(
            $dev_acnt->customer_id === $prod->customer_id,
            'device account and product does not belongs to same customer'
        );
    }
}
